//
//  XMLHomeTableViewController.swift
//  Weibo
//
//  Created by mac on 16/5/10.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
private let reuseID:String = "home"

class XMLHomeTableViewController: XMLVisitorTableViewController {
    
//    var homeArray :[XMLHome]?
    private lazy var homeViewModel :XMLHomeViewModel = XMLHomeViewModel()
    //上拉下载
    private lazy var pullUpView :UIActivityIndicatorView = {
    
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        
        view.color = UIColor.orangeColor()
        
        return view
    }()
    //下拉刷新1
    private lazy var refreshCtr :UIRefreshControl = {
    
        let control = UIRefreshControl()
        
        return control
    }()
    //下拉刷新2
    private lazy var refreshView :CZRefreshControl = {
    
        let view = CZRefreshControl()
        return view
    }()
    
    //  tip动画的控件
    private lazy var tipLabel: UILabel = {
        let label = UILabel(textColor: UIColor.whiteColor(), fontSize: 14)
        label.textAlignment = .Center
        label.backgroundColor = UIColor.orangeColor()
        label.text = "123"
        label.hidden = true
        return label
        
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        if isLogin {
//            requestData()
            loadHomeData()
            registerCell()
            
        }else {
        
            visitorView?.modifyVisitorInfo(nil, imageName: nil)
        }
    }
    
    private func loadHomeData() {
    
        homeViewModel.requestData(pullUpView.isAnimating(),complete: { (isSuccess,message) -> () in
            if !self.pullUpView.isAnimating() {
            
                self.startAnimate(message)
                
            }
            
            if isSuccess {
                
                self.tableView.reloadData()
            }
        })
    }
    //执行tipLabel的动画
    private func startAnimate(message :String) {
        
        if tipLabel.hidden == false {
        
            return
        }
    
        tipLabel.text = message
        tipLabel.hidden = false
        UIView.animateWithDuration(1, animations: { () -> Void in
            self.tipLabel.transform = CGAffineTransformMakeTranslation(0, self.tipLabel.frame.size.height)
            }) { (_) -> Void in
                UIView.animateWithDuration(1, animations: { () -> Void in
                    self.tipLabel.transform = CGAffineTransformIdentity
                    }, completion: { (_) -> Void in
                        self.tipLabel.hidden = true
                })
        }
        
        
    }
    
    private func endRefreshing() {
    
        pullUpView.stopAnimating()
        
        refreshCtr.endRefreshing()
        
        refreshView.endRefreshing()
        
    }
    
    private func registerCell() {
    
        tableView.registerClass(XMLHomeCell.self, forCellReuseIdentifier: reuseID)
//        tableView.rowHeight = 200
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 200
        
        tableView.tableFooterView = pullUpView
        pullUpView.sizeToFit()
        //第一种下拉刷新方式
//        refreshCtr.addTarget(self, action: "pullDownRefresh", forControlEvents: .ValueChanged)
//        self.refreshControl = refreshCtr
        //第二天下拉刷新方式
//        tableView.addSubview(refreshCtr)
//        tableView.addSubview(refreshView)
//        refreshView.addTarget(self, action: "pullDownRefresh", forControlEvents: .ValueChanged)
        
        
        let pullDownView = XMLRefreshControl()
        tableView.addSubview(pullDownView)
        pullDownView.addTarget(self, action: "pullDownRefreshData:", forControlEvents: .ValueChanged)
        
        
        if let nav = navigationController {
        
            tipLabel.frame = CGRectMake(0, CGRectGetMaxY(nav.navigationBar.frame) - 35, tableView.frame.size.width, 35)
            
            nav.view.insertSubview(tipLabel, belowSubview: nav.navigationBar)
        }
    }
    
    @objc private func pullDownRefreshData(refreshControl :XMLRefreshControl) {
    
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(2 * NSEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
//            
//        }
        loadHomeData()
        refreshControl.endRefresh()
    }
    
    @objc private func pullDownRefresh() {
     
    
        self.loadHomeData()
        endRefreshing()
        
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(2 * NSEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
//            
//            self.loadHomeData()
//            
//            self.refreshCtr.endRefreshing()
//        }
        
    }

//    func requestData() {
//    
//        XMLNetWorkTools.sharedTools.requestHomeData((XMLUserAcountViewModel.sharedUserAcountViewModel.userAcount?.access_token)!) { (response, error) -> () in
//            if error != nil {
//            
//                print("网络请求异常")
//            }
////            print(response)
//            guard let dict = response as? [String :AnyObject] else {
//                
//                print("不是字典类型")
//                return
//            }
//            
//            guard let dictArray = dict["statuses"] as? [[String :AnyObject]] else {
//            
//                return
//            }
//            var nmArray = [XMLHome]()
//            for dict in dictArray {
//                let home = XMLHome(dict: dict)
//                nmArray.append(home)
//            }
//            self.homeArray = nmArray
//            self.tableView.reloadData()
//        }
//    }

}

extension XMLHomeTableViewController {

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return homeViewModel.homeArray?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier(reuseID, forIndexPath: indexPath) as! XMLHomeCell
        
        cell.homeCellViewModel = homeViewModel.homeArray![indexPath.row]
        cell.selectionStyle = .None
        
        return cell
        
    }
    
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        
//        print(indexPath.row)
        
        if indexPath.row == homeViewModel.homeArray!.count - 1 && !pullUpView.isAnimating(){
        
            print("我是最后一个cell")
            //开启动画
            pullUpView.startAnimating()
            
            //请求数据
            
            loadHomeData()
        }
    }
    
    
}



